package com.gan.bi.job.once;

import com.gan.bi.exception.BusinessException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 初始化队列
 *
 */
// todo 取消注释开启任务
// @Component
@Slf4j
public class MqInit implements CommandLineRunner {
    private static final String EXCHANGE_NAME = "ai_exchange";

    @Override
    public void run(String... args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        String queueName = "";
        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            channel.exchangeDeclare(EXCHANGE_NAME,"direct");

            queueName = "ai_queue";
            channel.queueDeclare(queueName,true,false,false,null);
            channel.queueBind(queueName,EXCHANGE_NAME,"ai");
        } catch (IOException | TimeoutException e) {
            log.error("队列初始化失败!");
            throw new BusinessException("队列初始化失败!");
        }
        log.info("队列" + queueName + "初始化成功!");
    }
}
